package com.scott.spring.ch04_05.service;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author 黄后林
 * @version 1.0
 * @date 2021-12-15 15:48:16
 */
@Service
public class MySQLService implements InitializingBean {
    public MySQLService() {
        System.out.println("--------MySQLService--------");
    }

    //1 连接数据库的场景

    //2 而连接数据库只要1次=单列 @Service


    public void xx(){
        System.out.println("-------");
    }

    // 需求：
    // 1：要容器启动完毕之后自动帮我们去创建MySQLService类的对象
    // 2：然后调用getConnection拿到1个数据库连接
    public Connection getConnection() throws Exception{
        System.out.println("------------#getConnection------------");

        // 1 先创建MySQLService类的对象 Spring容器去做
        // 2 调用getConnection  需求：因为我要连接数据库 希望Spring容器在创建完这个类的对象后
        // 3 立刻马上调用getConnection方法
        String username="root";
        String password="root";
        String driver="com.mysql.cj.jdbc.Driver";
        String url="jdbc:mysql://192.168.1.233:3306/crm-dev?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";

        Class.forName(driver);
        Connection connection = DriverManager.getConnection(url, username, password);
        return connection;



    }


    private Connection connection;

    @Override
    public void afterPropertiesSet() throws Exception {

        //AOP = 扩展点
        String username="root";
        String password="root";
        String driver="com.mysql.cj.jdbc.Driver";
        String url="jdbc:mysql://192.168.1.233:3306/crm-dev?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";

        Class.forName(driver);
        this.connection = DriverManager.getConnection(url, username, password);
        find();
        System.out.println("=======afterPropertiesSet==========");
    }

    public void find() throws Exception{
        PreparedStatement prepareStatement = connection.prepareStatement("select name from crm_user_t where id=100043");
        ResultSet resultSet = prepareStatement.executeQuery();
        resultSet.next();
        String name = resultSet.getString("name");
        System.out.println(name);
    }
}
